package com.custom.lessonstudy.di;


import com.blankj.utilcode.util.SPUtils;
import com.custom.lessonstudy.BuildConfig;


import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by cyb on 2018/11/21.
 * 创建请求对象
 */
public class RetrofitHttp {
    private static int CONNECT_TIMEOUT = 60;
    private static int READ_TIMEOUT = 60;
    private static int WRITE_TIMEOUT =60;
    private static  OkHttpClient okHttpClient;
    private static retrofit2.Retrofit retrofit;
    private  static HttpInterceptor httpInterceptor;

    /**
     * 添加应用拦截器interceptor
     * @param interceptor
     * @return
     */
    public static OkHttpClient provideOkHttpClient(HttpInterceptor interceptor){
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
       httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        if (okHttpClient==null){
            okHttpClient =  new OkHttpClient.Builder().
                    connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS).
                    readTimeout(READ_TIMEOUT, TimeUnit.SECONDS).
                    writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS).
                    //添加拦截器
                    addInterceptor(interceptor).
                    retryOnConnectionFailure(true).
                    build();
        }

        return okHttpClient;
    }
    public static retrofit2.Retrofit provideRetrofit(){
        //拦截器
        if (httpInterceptor==null){
            httpInterceptor = new HttpInterceptor();
        }
        //请求
        if (retrofit==null){
            retrofit =   new retrofit2.Retrofit.Builder()
                    .baseUrl(BuildConfig.BASE_URL)
                    .client(provideOkHttpClient(httpInterceptor))
                    //添加数据解析
                    .addConverterFactory(GsonConverterFactory.create())
                    //支持RXJava返回
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }

       return retrofit;
    }
}
